<template>
  <el-tree-select ref="treeSelect" :props="cascaderProps" v-model="value" lazy :load="lazyLoad" multiple show-checkbox
    @check-change="getCurrentNode" :default-expanded-keys="expandedData" collapse-tags :check-on-click-node="true"
    node-key="value" collapse-tags-tooltip :disabled="disabled" @remove-tag="removeTag">
    <template #default="{ data }">
      <span>{{ data.name.split('-').slice(-1)[0] }}</span>
    </template>
  </el-tree-select>
</template>
<script setup>
import { getProvince, getChildArea } from "@/api/system/division"
import { getRole } from '@/api/building/taskManage'

const props = defineProps({
  checkedData: {
    type: Array,
    default: () => ([])
  },
  disabled: {
    type: [String, Boolean]
  }
})

const { proxy } = getCurrentInstance()
const value = ref([])
const cascaderProps = {
  value: 'value',
  label: 'name',
  isLeaf: 'isLeaf'
}
const emits = defineEmits(['getAreaValue'])
// const options = ref([{ value: 'all', name: '中华人民共和国', children: [] }])
const options = ref([])
const optionsData = ref([])
const expandedData = ref()
const roleData = ref({})

const lazyLoad = async (node, resolve) => {
  const { level } = node
  resolve(options.value)
  roleData.value = await getRole()
  switch (roleData.value.data.role) {
    case 'qh_gj_role':
      countryOption(level, node, resolve)
      break;
    case 'qh_province_role':
      provinceOption(level, node, resolve)
      break;
    case 'qh_city_role':
      cityOption(level, node, resolve)
      break;
    case 'ph_county_role':
      countyOption(level, node, resolve)
      break;
    default:
      break;
  }
  // if (level == 1) {

  // if (level == 0) {
  //   getProvince().then(res => {
  //     const nodes = res.data.map(item => ({
  //       value: item.id,
  //       name: item.name
  //     }))
  //     optionsData.value = nodes
  //     resolve(nodes)
  //   })
  // } else {
  //   if (level > 2) return
  //   let prefixName = node.data.name
  //   getChildArea(node.data.value).then(res => {
  //     const nodes = res.data.map(item => ({
  //       // isLeaf: level >= 3 ? true : false,
  //       isLeaf: level >= 2 ? true : false,
  //       value: item.id,
  //       name: prefixName + '-' + item.name,
  //       'parent-value': node.data.value
  //     }))

  //     function getNodeData(options) {
  //       return options.reduce((prev, cur) => {
  //         if (cur.value == node.data.value) {
  //           cur.children = nodes
  //         }
  //         if (cur.children) {
  //           getNodeData(cur.children)
  //         }
  //         prev.push(cur)
  //         return prev
  //       }, [])
  //     }
  //     optionsData.value = getNodeData(optionsData.value)
  //     resolve(nodes)
  //   })
  // }
}

const countryOption = (level, node, resolve) => {
  if (level == 0) {
    getProvince().then(res => {
      const nodes = res.data.map(item => ({
        value: item.id,
        name: item.name
      }))
      optionsData.value = nodes
      resolve(nodes)
    })
  } else {
    getNextOption(level, node, resolve)
  }
}

const provinceOption = (level, node, resolve) => {
  const { data: { provinceId } } = roleData.value
  if (level == 0) {
    filterProvinceOption(resolve, provinceId)
  } else {
    getNextOption(level, node, resolve)
  }
}

const cityOption = (level, node, resolve) => {
  const { data: { provinceId, cityId } } = roleData.value
  if (level == 0) {
    filterProvinceOption(resolve, provinceId)
  } else {
    getNextOption(level, node, resolve, { cityId })
  }
}

const countyOption = (level, node, resolve) => {
  const { data: { provinceId, cityId, countyId } } = roleData.value
  if (level == 0) {
    filterProvinceOption(resolve, provinceId)
  } else {
    getNextOption(level, node, resolve, { cityId, countyId })
  }
}

const filterProvinceOption = (resolve, provinceId) => {
  getProvince().then(res => {
    const nodes = res.data.map(item => ({
      value: item.id,
      name: item.name
    })).filter(item => item.value == provinceId)
    optionsData.value = nodes
    resolve(nodes)
  })
}

const getNextOption = (level, node, resolve, idObj) => {
  if (level > 2) return
  let prefixName = node.data.name
  getChildArea(node.data.value).then(res => {
    let nodes = res.data.map(item => ({
      isLeaf: level >= 2 ? true : false,
      value: item.id,
      name: prefixName + '-' + item.name,
      'parent-value': node.data.value
    }))

    if (level == 1 && idObj?.cityId) {
      nodes = nodes.filter(item => item.value == idObj.cityId)
    }
    if (level == 2 && idObj?.countyId) {
      nodes = nodes.filter(item => item.value == idObj.countyId)
    }
    function getNodeData(options) {
      return options.reduce((prev, cur) => {
        if (cur.value == node.data.value) {
          cur.children = nodes
        }
        if (cur.children) {
          getNodeData(cur.children)
        }
        prev.push(cur)
        return prev
      }, [])
    }
    optionsData.value = getNodeData(optionsData.value)
    resolve(nodes)
  })
}

let checkNodes = ref([])
const getCurrentNode = () => {
  let curCheckNodes = proxy.$refs.treeSelect.getCheckedNodes()
  let parentNum = curCheckNodes.map(item => {
    let num = 0
    num = curCheckNodes.filter(item1 => item1['parent-value'] == item.value).length
    return num
  })
  let filterNodes = curCheckNodes.filter((item, index) => parentNum[index] == 0)
  checkNodes.value = formData(filterNodes)
  emits('getAreaValue', checkNodes.value)
}
const removeTag = (val) => {
  let curCheckNodes = proxy.$refs.treeSelect.getCheckedNodes()
  let removeIndex = curCheckNodes.findIndex(item => item.value == val)
  curCheckNodes.splice(removeIndex, 1)

  let nodeIndex = checkNodes.value.findIndex(item => item.pid == val || item.cid == val || item.id == val)
  checkNodes.value.splice(nodeIndex, 1)
  emits('getAreaValue', checkNodes.value)
}

// [[省、市、县]]
let flag = false
const getCheckedData = (data, target, index, test = []) => {
  data.map(item => {
    if (!flag) {
      test[index] = item
      if (item.value == target) {
        test = test.slice(0, index + 1)
        flag = true
        return false
      } else {
        if (item.children && item.children.length > 0) {
          let next = index + 1
          test = getCheckedData(item.children, target, next, test)
        }
      }
    }
  })
  return test
}

const formData = (curCheckNodes) => {
  let data = []
  curCheckNodes.map((item, index) => {
    flag = false
    let cur = getCheckedData(optionsData.value, item.value, 0, data[index])
    data[index] = cur
  })
  return updateCheckedData(data)
}

// 省市县field对应
const updateCheckedData = (data) => {
  let newData = []
  data.map((item, num) => {
    return item.map((itemChild, index) => {
      if (index == 0) {
        newData[num] = {
          pid: itemChild.value,
          ppName: itemChild.name
        }
      } else if (index == 1) {
        newData[num] = {
          ...newData[num],
          cid: itemChild.value,
          cityName: itemChild.name.split('-').slice(-1)[0]
        }
      } else if (index == 2) {
        newData[num] = {
          ...newData[num],
          id: itemChild.value,
          name: itemChild.name.split('-').slice(-1)[0]
        }
      }
    })
  })

  return newData
}

// watch(() => props.checkedData, () => {
//   expandedData.value = []
//   expandedData.value = [...new Set(props.checkedData.reduce((prev, cur) => {
//     cur.pid && prev.push(cur.pid)
//     cur.cid && prev.push(cur.cid)
//     return prev
//   }, []))]
//   value.value = props.checkedData.map(item => item.id || item.cid || item.pid)
//   console.log(value)
// }, {immediate: true, deep: true})

watchEffect(() => {
  expandedData.value = []
  expandedData.value = [...new Set(props.checkedData.reduce((prev, cur) => {
    cur.pid && prev.push(cur.pid)
    cur.cid && prev.push(cur.cid)
    return prev
  }, []))]
  value.value = props.checkedData.map(item => item.id || item.cid || item.pid)
})

defineExpose({
  checkNodes
})
</script>
<style scoped></style>